#!/bin/bash

# 要删除的目标文件
DEST_FILES="/usr/local/tomcat-8080/webapps/javis*"
# 打包生成的文件名
CURRENT_FILE_NAME="./javis-web/target/javis-web.war"
# 想要的文件名
DEST_FILE_NAME="./javis-web/target/javis.war"
# 目标webapps目录
DEST_PACKAGE_DIR="/usr/local/tomcat-8080/webapps/"

TOMCAT_BIN="/usr/local/tomcat-8080/bin/"

## 判断是否执行成功
check_result() {
    if  [ "$1" != "0" ] ; then
        exit -1
    fi
}

## 检测并杀掉Tomcat进程
check_kill_tomcat() {
   sleep $1
   pid=`ps aux | grep tomcat | grep -v grep | grep -v retomcat | awk '{print $2}'`
   if [ -n "$pid" ];  then
      echo ========kill tomcat begin==============
      echo "tomcat pid = " $pid
      kill -9 $pid
      echo ========kill tomcat end==============
   fi
}
## 拉取最新代码
git pull

check_result $?

## 重新打包
rm -rf target
mvn package -Dmaven.test.skip=true

check_result $?

## 拷贝war包到目标目录
rm -rf ${DEST_FILES}
mv ${CURRENT_FILE_NAME} ${DEST_FILE_NAME}
mv ${DEST_FILE_NAME} ${DEST_PACKAGE_DIR}

check_result $?

## 重启tomcat
cd ${TOMCAT_BIN}

start_time=`date +%s`

pid=`ps aux | grep tomcat | grep -v grep | grep -v retomcat | awk '{print $2}'`
echo $pid
if [ -n "$pid" ]; then
   echo "--> shutdown.sh"
   ./shutdown.sh
   check_kill_tomcat 1
   echo "--> startup.sh"
   ./startup.sh
else
    echo "--> startup.sh"
    ./startup.sh
fi

end_time=`date +%s`
sum=$(( $end_time-$start_time ))
echo "total consuming $sum ms"

jps